import java.util.concurrent.locks.StampedLock;

public class StampedLockDemo {

    private static double x, y;

    private static final StampedLock sl = new StampedLock();

    // an exclusively locked method
    public static void move(double deltaX, double deltaY) {
        long stamp = sl.writeLock();
        try {
            x += deltaX;
            y += deltaY;
        } finally {
            sl.unlockWrite(stamp);
        }
    }


    // A read-only method
    public static void distanceFromOrigin() {
        long stamp = sl.tryOptimisticRead();
        double currentX = x, currentY = y;
        if (!sl.validate(stamp)) {
            stamp = sl.readLock();
            try {
                currentX = x;
                currentY = y;
            } finally {
                sl.unlockRead(stamp);
            }
        }
        System.out.println(Math.sqrt(currentX * currentX + currentY * currentY));
    }

    // upgrade
    public static void moveIfAtOrigin(double newX, double newY) {
        // Could instead start with optimistic, not read mode
        long stamp = sl.readLock();
        try {
            while (x == 0.0 && y == 0.0) {
                long ws = sl.tryConvertToWriteLock(stamp);
                if (ws != 0L) {
                    stamp = ws;
                    x = newX;
                    y = newY;
                    break;
                } else {
                    sl.unlockRead(stamp);
                    stamp = sl.writeLock();
                }
            }
        } finally {
            sl.unlock(stamp);
        }
    }

    public static void main(String[] args) {
        new Thread(() -> StampedLockDemo.move(1,1), "move-thread").start();
        new Thread(StampedLockDemo::distanceFromOrigin, "distanceFromOrigin-thread").start();
        new Thread(() -> StampedLockDemo.moveIfAtOrigin(1, 1), "moveIfAtOrigin-thread").start();
    }

}
